import {  getNowFormatDate, compareObject } from '../../../../assets/js/util.js'
import echarts from 'echarts'
export default {
    data() {
        return {
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: '',
                uid: ''
            },
            title: '实时：广告位数据',
            agents: [],
            adUrls: [],
            attrs: [],
            channels: [],
            settlWays: [],
            adPlaces: [],
            platForms: [],
            activeIndex: 0,
            ruleForm: {
                date: '',
                agent: '',
                platForm: '',
                adUrl: '',
                attr: '',
                channel: '',
                settlWay: '',
                adPlace: ''
            },
            // 图表配置
            pay: {
                color: ['#2eb398','#79bde9','#9d79d8'],
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    top: '10px',
                    data:[]
                },
                grid: {
                    left: '2%',
                    right: '2%',
                    bottom: '15%',
                    containLabel: true
                },
                toolbox: {
                    right: '20',
                    feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    magicType: {
                        type: ['line', 'bar']
                    },
                    restore: {},
                    saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    data: [],
                    axisLabel:{
                        margin:20,
                    },
                },
                yAxis: {
                    type: 'value',
                    // max: 10000
                },
                dataZoom: [{
                    handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                    handleSize: '80%',
                    handleStyle: {
                        color: '#fff',
                        shadowBlur: 3,
                        shadowColor: 'rgba(0, 0, 0, 0.6)',
                        shadowOffsetX: 2,
                        shadowOffsetY: 2
                    }
                    }],
                series: [{
                    name: '1',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol:'circle',
                }, {
                    name: '2',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol:'roundRect',
                }, {
                    name: '3',
                    type: 'line',
                    smooth: true,
                    data: [],
                    symbol:'triangle',
                }]
            },
            // 实时数据显示
            realLoadShow: false, 
            hoursHead: [{
                    "prop": "dateStr",
                    "label": "时间"
                },
                {
                    "prop": "actEquipment",
                    "label": "激活设备"
                },
                {
                    "prop": "newActive",
                    "label": "实际激活"
                },
                {
                    "prop": "newEquipment",
                    "label": "新增设备"
                },
                {
                    "prop": "accountActive",
                    "label": "新增/激活"
                },
                {
                    "prop": "newAccount",
                    "label": "新增账号数"
                },
                {
                    "prop": "newPayAccount",
                    "label": "新增付费账号"
                },
                {
                    "prop": "newPay",
                    "label": "新增付费金额"
                },
                {
                    "prop": "newPayRate",
                    "label": "新增付费率"
                },
                {
                    "prop": "arpu",
                    "label": "ARPU"
                },
            ],
            hoursData: [],
            hoursDatas: [],
            realTmHead: [{
                    "prop": "dateStr",
                    "label": "时间"
                },
                {
                    "prop": "id",
                    "label": "广告url"
                },
                {
                    "prop": "advName",
                    "label": "广告名称"
                },
                {
                    "prop": "actEquipment",
                    "label": "激活设备"
                },
                {
                    "prop": "newActive",
                    "label": "实际激活"
                },
                {
                    "prop": "newEquipment",
                    "label": "新增设备"
                },
                {
                    "prop": "accountActive",
                    "label": "新增/激活"
                },
                {
                    "prop": "newAccount",
                    "label": "新增账号数"
                },
                {
                    "prop": "newPayAccount",
                    "label": "新增付费账号"
                },
                {
                    "prop": "newPay",
                    "label": "新增付费金额"
                },
            ],
            loading: false,
            searchable: false,
            realTmData: [],
            realTmDatas: [],
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,

            /*当前页显示数量*/
            pageSize2: 10,
            /*每页显示的数量*/
            pageSizes2: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal2: 0,
            /*分页器*/
            currentPage2: 1,
            //4个图表的数据
            echartsDataArr:  []
        }
    },
    computed: {

    },
    methods: {
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
            //初始化
        _init() {
            var arr = ['tbecharts'];
            for(var x=0; x<arr.length;x++){
                this[arr[x]+'Charts'] = echarts.init(document.getElementById(arr[x]));
                this[arr[x]+'Charts'].setOption(this.pay);
            }
            window.addEventListener('resize', function() {
                var resizeArr = ['tbechartsCharts']
                for(var j in resizeArr){
                    this[resizeArr[j]].resize();
                }
            }.bind(this))
        },
        dateChange(val) {
            this.ruleForm.date = val;
        },
        agentChange() {

        },
        attrChange() {

        },
        platFormChange() {

        },
        channelChange() {

        },
        settlWayChange() {

        },
        adPlaceChange() {

        },
        adUrlChange() {

        },
        loads() {
            this.loading = !this.loading; //加载中
            this.searchable = !this.searchable; //查询按钮不可用
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.tableControl();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.tableControl();
        },
        tableControl() {
            this.hoursData = this.hoursDatas.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        handleSizeChange2(val) {
            this.pageSize2 = val;
            this.tableControl2();
        },
        handleCurrentChange2(val) {
            this.currentPage2 = val;
            this.tableControl2();
        },
        tableControl2() {
            this.realTmData = this.realTmDatas.slice((this.currentPage2 - 1) * this.pageSize2, this.currentPage2 * this.pageSize2)
        },
        /*==================获取下拉列表数据========================*/
        getData() {
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=initParam`, {
                params: { 'ps': `uid=${this.DP.uid}` }
            }).then(function(res) {
                var data = JSON.parse(JSON.parse(res.body));
                if (parseInt(data['res']) === 0) {
                    /*=====获取代理商数据======*/
                    for (var i = 0; i < data.agent.length; i++) {
                        var obj = {};
                        obj.id = data.agent[i];
                        obj.agentName = data.agent[i];
                        this.agents.push(obj);
                    }
                    /*=====获取平台======*/
                    for (var i = 0; i < data.platform.length; i++) {
                        var obj = {};
                        obj.id = data.platform[i];
                        obj.platFormName = data.platform[i];
                        this.platForms.push(obj);
                    }
                    /*=====获取广告url======*/
                    for (var i = 0; i < data.surl.length; i++) {
                        var obj = {};
                        obj.id = data.surl[i];
                        obj.adUrlName = data.surl[i];
                        this.adUrls.push(obj);
                    }
                    /*=====获取归属======*/
                    for (var i = 0; i < data.affiliation.length; i++) {
                        var obj = {};
                        obj.id = data.affiliation[i];
                        obj.attrName = data.affiliation[i];
                        this.attrs.push(obj);
                    }
                    /*=====获取渠道名称======*/
                    for (var i = 0; i < data.channelName.length; i++) {
                        var obj = {};
                        obj.id = data.channelName[i];
                        obj.channelName = data.channelName[i];
                        this.channels.push(obj);
                    }
                    /*=====获取结算方式======*/
                    for (var i = 0; i < data.paytype.length; i++) {
                        var obj = {};
                        obj.id = data.paytype[i];
                        obj.settlWayName = data.paytype[i];
                        this.settlWays.push(obj);
                    }
                    /*=====获取广告位置======*/
                    for (var i = 0; i < data.advPosition.length; i++) {
                        var obj = {};
                        obj.id = data.advPosition[i];
                        obj.adPlaceName = data.advPosition[i];
                        this.adPlaces.push(obj);
                    }
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*====================时间格式化转换函数============================*/
        formatDate(date) {
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? '0' + m : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            return y + '-' + m + '-' + d;
        },
        /*===============切换图表展示数据====================*/
        navChange(n){
            this.activeIndex = n;
            this.echartsData(this.echartsDataArr[n]);
        },
        /*==================获取表格数据========================*/
        getTableData(data) {
            this.loads();
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `day=${data.date}&agent=${data.agent}&platform=${data.platForm}&surl=${data.adUrl}&affiliation=${data.attr}&channelName=${data.channel}&paytype=${data.settlWay}&advPosition=${data.adPlace}&uid=${this.DP.uid}` }
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data['res']) === 0) {
                    this.hoursDatas = data.payHourDatas;
                    this.realTmDatas = data.payMinDatas;
                    this.dataTotal = data.payHourDatas.length;
                    this.dataTotal2 = data.payMinDatas.length;
                    this.echartsDataArr.push(data.activeChart);
                    this.echartsDataArr.push(data.newActChart);
                    this.echartsDataArr.push(data.newAccountChart);
                    this.echartsDataArr.push(data.newPayChart);
                    this.echartsData(this.echartsDataArr[Number(this.activeIndex)]);
                    this.tableControl();
                    this.tableControl2();
                } else {
                    this.errorFun(data['msg'])
                }
            })
        },
        /*===========================查询功能===============================*/
        search() {
            this.loads();
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=search`, {
                params: { 'ps': `day=${this.ruleForm.date}&agent=${this.ruleForm.agent}&platform=${this.ruleForm.platForm}&surl=${this.ruleForm.adUrl}&affiliation=${this.ruleForm.attr}&channelName=${this.ruleForm.channel}&paytype=${this.ruleForm.settlWay}&advPosition=${this.ruleForm.adPlace}&uid=${this.DP.uid}` },
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data.res) === 0) {
                    if (data.length == 0) {
                        this.errorFun('查询结果为空！')
                    } else {
                        this.echartsDataArr = [];
                        this.hoursDatas = data.payHourDatas;
                        this.realTmDatas = data.payMinDatas;
                        this.dataTotal = data.payHourDatas.length;
                        this.dataTotal2 = data.payMinDatas.length;
                        this.echartsDataArr.push(data.activeChart);
                        this.echartsDataArr.push(data.newActChart);
                        this.echartsDataArr.push(data.newAccountChart);
                        this.echartsDataArr.push(data.newPayChart);
                        this.echartsData(this.echartsDataArr[Number(this.activeIndex)]);
                        this.tableControl();
                        this.tableControl2();
                    }
                } else {
                    this.errorFun(data.msg)
                }
            })
        },
        judgeUnderfind(d,key) {
            if(d[key] == undefined){
              var data1 = {
                "columnkeys":[],
                "names":[],
                "data":[[]]
              }
            }else{
              var data1 = d[key]['jsonStr'] ;
            }
            return data1
        },
        // 改变表数据
        echartsData(d) {
            // 新增付费获取到数据渲染
            var data = d.jsonStr;
            this.tbechartsCharts.setOption({
                legend: {
                    data: data['names']
                },
                xAxis: {
                    data: data['columnkeys']
                },
                series: [
                    {
                        name: data['names'][0],
                        type: 'line',
                        data: data['data'][0]
                    },
                    {
                        name: data['names'][1],
                        type: 'line',
                        data: data['data'][1]
                    },
                ]
            })
        },
        /*===========================高级查询功能===============================*/
        gjSearch() {
            this.loads();
            this.$http.jsonp(`${this.SRC}data/get.do?p=${this.DP.p}&f=${this.DP.f}&a=searchMin`, {
                params: { 'ps': `day=${this.ruleForm.date}&agent=${this.ruleForm.agent}&platform=${this.ruleForm.platForm}&surl=${this.ruleForm.adUrl}&affiliation=${this.ruleForm.attr}&channelName=${this.ruleForm.channel}&paytype=${this.ruleForm.settlWay}&advPosition=${this.ruleForm.adPlace}&uid=${this.DP.uid}` },
            }).then(function(res) {
                var data = JSON.parse(res.body);
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                this.loads();
                if (parseInt(data.res) === 0) {
                    if (data.length == 0) {
                        this.errorFun('查询结果为空！')
                    } else {
                        this.realTmDatas = data.payMinDatas;
                        this.dataTotal2 = data.payMinDatas.length;
                        this.tableControl2();
                    }
                } else {
                    this.errorFun(data.msg)
                }
            })
        },
        // 表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.hoursDatas.sort(compareObject(column.prop, false));
            } else { //正序
                this.hoursDatas.sort(compareObject(column.prop, true));
            }
            this.tableControl();
        },
        // 表格排序
        sortChange2(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.realTmDatas.sort(compareObject(column.prop, false));
            } else { //正序
                this.realTmDatas.sort(compareObject(column.prop, true));
            }
            this.tableControl2();
        },
        // 表格下载
        excel(tableIndex, sheet) {
            var that = this;
            var table,tableAll = [];
            if(tableIndex === 1){
                table = this.hoursHead;
                tableAll = this.hoursDatas;
            }else{
                table = this.realTmHead;
                tableAll = this.realTmDatas;
            }
            that.xlsxTitle = sheet;
            that.downloadExl(table, tableAll,that.xlsxTitle,sheet);
            
        },
    },
    created() {},
    mounted() {
        // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        this.DP.uid = localStorage.getItem('ZULONGBIUSERID');
        this.ruleForm.date = new Date();
        this.ruleForm.date = this.formatDate(this.ruleForm.date);
        this.getData();
        this._init();
        this.getTableData(this.ruleForm);
    }
}